package com.xzy.springboot.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class PaymentService {


    public String PaymentOk(Integer id){

        log.info("线程池:  "+Thread.currentThread().getName()+"id:  "+id+"操作正常");
        return "线程池:  "+Thread.currentThread().getName()+"id:  "+id+"操作正常";
    }


    //单一方法服务降级
    @HystrixCommand(fallbackMethod = "PaymentTimeoutfallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500")
    })
    public String PaymentTimeout(Integer id){
        int time=3;
        try {
            Thread.sleep(time*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("线程池:  "+Thread.currentThread().getName()+"id:  "+id+"超时:"+time+"秒");
        return "线程池:  "+Thread.currentThread().getName()+"id:  "+id+"超时:"+time+"秒";
    }


    public String PaymentTimeoutfallback(Integer id){
        return "线程池:  "+Thread.currentThread().getName()+"id:  "+id+"     生产者侧降级服务;       ";
    }


    /*服务熔断:
    * 1.调用失败会触发降级,而降级会调用fallback方法
    * 2.但无论如何降级调用流程都一定是先调用正常方法再调用fallback方法
    * 3.假如单位时间内调用失败次数过多,也就是降级次数过多,则触发熔断
    * 4.熔断以后就会跳过正常方法调用直接调用fallback
    * 5所谓"熔断后服务不可用"就是因为跳过了正常方法调用*/


    @HystrixCommand(fallbackMethod = "paymentfusing_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")})
    public String paymentfusing(Integer id){

        if (id<0){
            throw new RuntimeException("*********id为负");
        }

        String s = IdUtil.simpleUUID();

        return "线程池:  "+Thread.currentThread().getName()+"id:  "+id+" 调用成功 ";
    }
    /*熔断兜底*/
    public String paymentfusing_fallback(Integer id){
        return "线程池:  "+Thread.currentThread().getName()+"id:  "+id+"   服务降级     ";
    }


}
